<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>教师端首页 - 学生荣誉信息管理系统</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入ECharts库 -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <style>
        body { background: #f6fbff; font-family: 'Segoe UI', Arial, sans-serif; color: #222; margin:0; }
        .header {
            background: #1976d2; color: #fff; display: flex; align-items: center; justify-content: space-between;
            padding: 0 32px; height: 64px; box-shadow: 0 2px 8px rgba(25,118,210,0.10); position: sticky; top: 0; z-index: 10;
        }
        .header .logo { display: flex; align-items: center; gap: 12px; }
        .header .logo img { width: 38px; height: 38px; border-radius: 50%; background: #fff; }
        .header .logo span { font-size: 22px; font-weight: bold; letter-spacing: 2px; }
        .header .user-info { display: flex; align-items: center; gap: 18px; }
        .header .user-info span { font-size: 16px; }
        .header .logout-btn { background: rgba(255,255,255,0.18); border: none; color: #fff; padding: 7px 18px; border-radius: 7px; cursor: pointer; font-size: 15px; transition: background 0.2s; }
        .header .logout-btn:hover { background: rgba(255,255,255,0.32); }
        .nav-bar { background: #fff; border-bottom: 1.5px solid #e3eaf2; }
        .nav-bar ul { display: flex; gap: 24px; margin: 0; padding: 0 32px; list-style: none; }
        .nav-bar li { padding: 14px 28px; cursor: pointer; border-radius: 8px 8px 0 0; font-size: 16px; color: #1976d2; transition: background 0.2s, color 0.2s; }
        .nav-bar li.active, .nav-bar li:hover { background: #1976d2; color: #fff; }
        .container { max-width: 1200px; margin: 32px auto; padding: 0 18px; }
        .search-bar { display: flex; justify-content: center; margin: 28px 0 18px 0; }
        .search-bar input { width: 280px; padding: 11px; border-radius: 8px 0 0 8px; border: 1.5px solid #b6d0ee; font-size: 15px; outline: none; }
        .search-bar button { padding: 11px 28px; border-radius: 0 8px 8px 0; background: #1976d2; color: #fff; border: none; font-size: 15px; cursor: pointer; transition: background 0.2s; }
        .search-bar button:hover { background: #1256a6; }
        .main-flex { display: flex; gap: 32px; align-items: flex-start; }
        .honor-list { flex: 2; display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 240px)); gap: 18px; justify-content: center; }
        .honor-card {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 4px 16px rgba(25,118,210,0.08);
            padding: 14px;
            cursor: pointer;
            transition: box-shadow 0.2s, transform 0.2s;
            display: flex;
            flex-direction: column;
            align-items: center;
            text-align: center;
            height: 220px;
            min-height: 220px;
            max-height: 240px;
            justify-content: flex-start;
        }
        .honor-card:hover { box-shadow: 0 8px 24px rgba(25,118,210,0.16); transform: translateY(-2px) scale(1.02); }
        .honor-title { font-size: 18px; font-weight: bold; color: #1976d2; margin-bottom: 8px; }
        .honor-meta { color: #888; font-size: 14px; margin-bottom: 8px; }
        .honor-cert {
            width: 100%;
            max-width: 240px;
            height: 140px;
            object-fit: cover;
            border-radius: 8px;
            margin-bottom: 8px;
            align-self: center;
            transition: transform 0.22s cubic-bezier(.4,1.4,.6,1);
        }
        .honor-cert:hover {
            transform: scale(1.08);
            z-index: 2;
            box-shadow: 0 6px 18px rgba(25,118,210,0.13);
        }
        .honor-desc { color: #444; font-size: 15px; flex: 1; overflow: hidden; text-overflow: ellipsis; }
        .student-panel { flex: 1; background: #fff; border-radius: 12px; box-shadow: 0 4px 16px rgba(25,118,210,0.08); padding: 18px 12px 18px 12px; max-height: 600px; overflow-y: auto; }
        .student-panel h3 { color: #1976d2; font-size: 17px; margin-bottom: 12px; text-align: center; }
        .student-table { width: 100%; border-collapse: collapse; font-size: 14px; }
        .student-table th, .student-table td { padding: 8px 6px; border-bottom: 1px solid #e3eaf2; text-align: center; }
        .student-table th { background: #f6fbff; color: #1976d2; position: sticky; top: 0; z-index: 1; }
        .student-table tr:hover { background: #f0f7ff; cursor: pointer; }
        .empty-state { text-align: center; color: #888; padding: 60px 0; }
        
        /* 图表容器样式 */
        .chart-container {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 4px 16px rgba(25,118,210,0.08);
            padding: 20px;
            margin-bottom: 30px;
        }
        .chart-title {
            color: #1976d2;
            font-size: 18px;
            font-weight: 500;
            margin-bottom: 15px;
            text-align: center;
        }
        .chart-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }
        .chart-item {
            height: 400px;
            border-radius: 8px;
            overflow: hidden;
        }
        @media (max-width: 900px) { 
            .main-flex { flex-direction: column; } 
            .student-panel { max-height: none; margin-bottom: 24px; }
            .chart-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="logo">
            <img src="/static/imges/圆形.png" alt="logo">
            <span>学生荣誉信息管理系统</span>
        </div>
        <div class="user-info">
            <span id="teacherName">教师</span>
            <button class="logout-btn" onclick="logout()">退出登录</button>
        </div>
    </div>
    <nav class="nav-bar">
        <ul id="typeTabs">
            <li class="active" data-type="">全部</li>
            <li data-type="学科竞赛">学科竞赛</li>
            <li data-type="文体活动">文体活动</li>
            <li data-type="社会实践">社会实践</li>
            <li data-type="创新创业">创新创业</li>
            <li data-type="其他">其他</li>
            <li data-type="student-list" id="studentListTab">学生列表</li>
            <li data-type="charts" id="chartsTab">数据统计</li>
        </ul>
    </nav>
<div class="container">
        <!-- 图表展示区域 -->
        <div id="charts-section" class="section" style="display: none;">
            <div class="chart-container">
                <div class="chart-title">学生荣誉数据统计</div>
                <div class="chart-grid">
                    <div class="chart-item" id="honorTypeChart"></div>
                    <div class="chart-item" id="honorTrendChart"></div>
                </div>
            </div>
        </div>

        <div class="search-bar" id="searchBar">
            <input type="text" id="searchInput" placeholder="输入学生姓名或学号，回车或点搜索">
            <button onclick="searchStudent()">搜索</button>
        </div>
        <div class="main-flex" id="mainFlex">
            <div class="honor-list" id="honorList">
                <div class="empty-state">加载中...</div>
            </div>
            <div class="student-panel" id="studentPanel" style="display:none;">
                <h3>学生列表</h3>
                <table class="student-table" id="studentTable">
                    <thead>
                        <tr><th>学号</th><th>姓名</th><th>性别</th><th>年级</th><th>班级</th><th>院系</th><th>电话</th><th>邮箱</th><th>注册时间</th></tr>
                    </thead>
                    <tbody id="studentTableBody">
                        <tr><td colspan="9">加载中...</td></tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <div id="imgPreviewModal" style="display:none;position:fixed;left:0;top:0;width:100vw;height:100vh;background:rgba(0,0,0,0.4);z-index:999;align-items:center;justify-content:center;">
      <img id="imgPreview" src="" style="max-width:90vw;max-height:90vh;border-radius:12px;box-shadow:0 4px 24px rgba(0,0,0,0.18);background:#fff;">
</div>
<script>
        // 顶部教师姓名展示（可从token或接口获取）
        document.getElementById('teacherName').textContent = localStorage.getItem('teacherName') || '教师';

function logout() {
    localStorage.removeItem('token');
            window.location.replace('/');
        }

        // 导航栏切换
        const typeTabs = document.querySelectorAll('#typeTabs li');
        typeTabs.forEach(tab => {
            tab.onclick = function() {
                typeTabs.forEach(t => t.classList.remove('active'));
                this.classList.add('active');
                if(this.dataset.type === 'student-list') {
                    document.getElementById('honorList').style.display = 'none';
                    document.getElementById('searchBar').style.display = 'none';
                    document.getElementById('studentPanel').style.display = '';
                    document.getElementById('charts-section').style.display = 'none';
                    loadStudents();
                } else if(this.dataset.type === 'charts') {
                    document.getElementById('honorList').style.display = 'none';
                    document.getElementById('searchBar').style.display = 'none';
                    document.getElementById('studentPanel').style.display = 'none';
                    document.getElementById('charts-section').style.display = 'block';
                    initCharts();
                } else {
                    document.getElementById('honorList').style.display = '';
                    document.getElementById('searchBar').style.display = '';
                    document.getElementById('studentPanel').style.display = 'none';
                    document.getElementById('charts-section').style.display = 'none';
                    loadHonors(this.dataset.type);
                }
            };
        });

        // 搜索功能
        document.getElementById('searchInput').addEventListener('keydown', function(e) {
            if(e.key === 'Enter') searchStudent();
        });
        function searchStudent() {
            const val = document.getElementById('searchInput').value.trim();
            if(!val) return;
            // 搜索时只显示该学生的荣誉
            document.getElementById('honorList').innerHTML = '<div class="empty-state">加载中...</div>';
    fetch('/api/teacher/honor/all', {
                headers: { 'Authorization': localStorage.getItem('token') || '' }
            })
            .then(r => r.json())
            .then(res => {
        if(res.code === 200) {
                    // 支持姓名或学号模糊匹配
                    const honors = res.honors.filter(h =>
                        (h.student_name && h.student_name.includes(val)) ||
                        (h.student_username && h.student_username.includes(val))
                    );
                    if(honors.length > 0) {
                        document.getElementById('honorList').innerHTML = honors.map(h => {
                            let certUrl = h.certificate_url || '';
                            let isImg = /\.(jpg|jpeg|png|gif|webp|svg)$/i.test(certUrl);
                            let certImg = isImg && certUrl
                                ? `<img src='${certUrl}' class='honor-cert' onclick='showCertImg("${certUrl}"); event.stopPropagation();'>`
                                : `<img src='/static/imges/honor.jpg' class='honor-cert' onclick='showCertImg("/static/imges/honor.jpg"); event.stopPropagation();'>`;
                            return `
                                <div class='honor-card'>
                                    <div class='honor-title'><a href="/teacher/honor/${h.id}" style="color:#1976d2;text-decoration:underline;cursor:pointer;">${h.title}</a></div>
                                    <div class='honor-meta'>${h.honor_type || ''} | ${h.date || ''} | ${h.student_name || ''}</div>
                                    ${certImg}
                                </div>
                            `;
                        }).join('');
                    } else {
                        document.getElementById('honorList').innerHTML = '<div class="empty-state">未找到该学生的荣誉</div>';
                    }
            } else {
                    document.getElementById('honorList').innerHTML = '<div class="empty-state">加载失败</div>';
                }
            })
            .catch(()=>{
                document.getElementById('honorList').innerHTML = '<div class="empty-state">加载失败</div>';
            });
        }

        // 加载荣誉（可按类型筛选）
        function loadHonors(type = '') {
            document.getElementById('honorList').innerHTML = '<div class="empty-state">加载中...</div>';
            fetch('/api/teacher/honor/all?type=' + encodeURIComponent(type), {
                headers: { 'Authorization': localStorage.getItem('token') || '' }
            })
            .then(r => r.json())
            .then(res => {
                if(res.code === 200 && res.honors.length > 0) {
                    document.getElementById('honorList').innerHTML = res.honors.map(h => {
                        let certUrl = h.certificate_url || '';
                        let isImg = /\.(jpg|jpeg|png|gif|webp|svg)$/i.test(certUrl);
                        let certImg = isImg && certUrl
                            ? `<img src='${certUrl}' class='honor-cert' onclick='showCertImg("${certUrl}"); event.stopPropagation();'>`
                            : `<img src='/static/imges/honor.jpg' class='honor-cert' onclick='showCertImg("/static/imges/honor.jpg"); event.stopPropagation();'>`;
                        return `
                            <div class='honor-card'>
                                <div class='honor-title'><a href="/teacher/honor/${h.id}" style="color:#1976d2;text-decoration:underline;cursor:pointer;">${h.title}</a></div>
                                <div class='honor-meta'>${h.honor_type || ''} | ${h.date || ''} | ${h.student_name || ''}</div>
                                ${certImg}
                            </div>
                        `;
                    }).join('');
                } else {
                    document.getElementById('honorList').innerHTML = '<div class="empty-state">暂无荣誉</div>';
                }
            })
            .catch(()=>{
                document.getElementById('honorList').innerHTML = '<div class="empty-state">加载失败</div>';
            });
        }

        // 加载学生列表
        function loadStudents() {
            fetch('/api/teacher/students', {
                headers: { 'Authorization': localStorage.getItem('token') || '' }
            })
            .then(r => r.json())
            .then(res => {
                if(res.code === 200 && res.students.length > 0) {
                    document.getElementById('studentTableBody').innerHTML = res.students.map(s => `
                        <tr onclick="viewStudentHonors('${s.username}')">
                            <td>${s.username}</td><td>${s.name}</td><td>${s.gender||''}</td><td>${s.grade||''}</td><td>${s.class_name||''}</td><td>${s.department||''}</td><td>${s.phone||''}</td><td>${s.email||''}</td><td>${s.created_at||''}</td>
                        </tr>
                    `).join('');
            } else {
                    document.getElementById('studentTableBody').innerHTML = '<tr><td colspan="9">暂无学生</td></tr>';
                }
            })
            .catch(()=>{
                document.getElementById('studentTableBody').innerHTML = '<tr><td colspan="9">加载失败</td></tr>';
            });
        }
        // 学生行点击跳转
        function viewStudentHonors(username) {
            window.location.href = '/static/student_main.html?student=' + encodeURIComponent(username);
        }

        // 初始化图表
        function initCharts() {
            // 获取荣誉数据
            fetch('/api/teacher/honor/all', {
                headers: { 'Authorization': localStorage.getItem('token') || '' }
            })
            .then(r => r.json())
            .then(res => {
                if(res.code === 200) {
                    createHonorTypeChart(res.honors);
                    createHonorTrendChart(res.honors);
                }
            })
            .catch(err => {
                console.error('加载荣誉数据失败:', err);
            });
        }

        // 创建荣誉类型分布图表
        function createHonorTypeChart(honors) {
            const chartDom = document.getElementById('honorTypeChart');
            const myChart = echarts.init(chartDom);
            
            // 统计各类型荣誉数量
            const typeStats = {};
            honors.forEach(honor => {
                const type = honor.honor_type || '其他';
                typeStats[type] = (typeStats[type] || 0) + 1;
            });
            
            const option = {
                title: {
                    text: '荣誉类型分布',
                    left: 'center',
                    textStyle: {
                        color: '#1976d2',
                        fontSize: 16
                    }
                },
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c} ({d}%)'
                },
                legend: {
                    orient: 'vertical',
                    left: 'left',
                    data: Object.keys(typeStats)
                },
                series: [
                    {
                        name: '荣誉类型',
                        type: 'pie',
                        radius: '50%',
                        data: Object.entries(typeStats).map(([name, value]) => ({
                            name,
                            value
                        })),
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            };
            
            myChart.setOption(option);
        }

        // 创建荣誉趋势图表
        function createHonorTrendChart(honors) {
            const chartDom = document.getElementById('honorTrendChart');
            const myChart = echarts.init(chartDom);
            
            // 按月份统计荣誉数量
            const monthStats = {};
            honors.forEach(honor => {
                if (honor.date) {
                    const date = new Date(honor.date);
                    const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
                    monthStats[monthKey] = (monthStats[monthKey] || 0) + 1;
                }
            });
            
            // 获取最近6个月的数据
            const months = [];
            const counts = [];
            const now = new Date();
            for (let i = 5; i >= 0; i--) {
                const date = new Date(now.getFullYear(), now.getMonth() - i, 1);
                const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
                months.push(monthKey);
                counts.push(monthStats[monthKey] || 0);
            }
            
            const option = {
                title: {
                    text: '荣誉提交趋势',
                    left: 'center',
                    top: 10,
                    textStyle: {
                        color: '#1976d2',
                        fontSize: 16
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                        label: {
                            backgroundColor: '#283b56'
                        }
                    }
                },
                legend: {
                    data: ['荣誉数量'],
                    top: 40
                },
                toolbox: {
                    show: true,
                    top: 40,
                    right: 20,
                    feature: {
                        dataView: { readOnly: false },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                grid: {
                    top: 80,
                    left: 60,
                    right: 60,
                    bottom: 60
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: months,
                    axisLabel: {
                        rotate: 45
                    }
                },
                yAxis: {
                    type: 'value',
                    scale: true,
                    name: '荣誉数量',
                    nameLocation: 'middle',
                    nameGap: 40,
                    boundaryGap: [0.2, 0.2]
                },
                series: [
                    {
                        name: '荣誉数量',
                        type: 'line',
                        data: counts,
                        smooth: true,
                        lineStyle: {
                            color: '#1976d2'
                        },
                        areaStyle: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [{
                                    offset: 0, color: 'rgba(25,118,210,0.3)'
                                }, {
                                    offset: 1, color: 'rgba(25,118,210,0.1)'
                                }]
                            }
                        }
                    }
                ]
            };
            
            myChart.setOption(option);
        }

        // 页面初始化
        loadHonors('');
        loadStudents();

        // 自动刷新学生列表（每30秒）
        setInterval(() => {
            if(document.getElementById('studentPanel').style.display !== 'none') {
                loadStudents();
            }
        }, 30000);
    </script>
    <script>
function showCertImg(url) {
    var modal = document.getElementById('imgPreviewModal');
    var img = document.getElementById('imgPreview');
    img.src = url;
    modal.style.display = 'flex';
    modal.onclick = function(e) {
        if(e.target === modal) modal.style.display = 'none';
    };
}
</script>
</body>
</html> 